<template>
  <div class="task-execute-view">
    <el-page-header @back="handleAbortTask">
      <template #content>
        <span class="text-large font-600 mr-3"> 任务巡视 ({{ currentTask?.taskName }}) </span>
      </template>
    </el-page-header>

    <div v-if="taskLoading" v-loading="true" class="loading-state"></div>

    <div v-else-if="currentTask" class="main-container">
      <div class="content-area">
        <div class="video-area">
          <div v-if="!selectedCameraId" class="video-placeholder">
            <el-icon><VideoCamera /></el-icon>
            <span>视频加载中...</span>
          </div>
          <div v-else :key="selectedCameraId" ref="videoPlayerContainer" style="width: 100%; height: 100%;"></div>
        </div>
        <div class="scale-bar-area">
          <div class="scale-bar-wrapper">
            <div class="scale-bar-text start">0m</div>
            <div class="scale-bar-text end">{{ currentTask.taskTrip || 0 }}m</div>
            <div class="scale-bar">
              <div class="scale-bar-progress" :style="{ width: agvPositionPercentage }"></div>
            </div>
            <el-tooltip content="AGV当前位置" placement="top">
              <div class="scale-bar-item scale-bar-agv" :style="{ left: agvPositionPercentage }">
                <el-icon><Van /></el-icon>
              </div>
            </el-tooltip>
            <el-tooltip
                v-for="flaw in processedLiveFlaws"
                :key="flaw.id"
                :content="`${flaw.flawName} @ ${flaw.flawDistance}m`"
                placement="top"
            >
              <div
                  class="scale-bar-item scale-bar-flaw"
                  :style="{ left: calculateFlawPosition(flaw.flawDistance) }"
              >
                <el-icon><Warning /></el-icon>
              </div>
            </el-tooltip>
          </div>
        </div>
      </div>

      <div class="sidebar">
        <el-card shadow="never" class="info-card">
          <template #header>
            <div class="card-header">控制台</div>
          </template>
          <div class="control-buttons">
            <el-select v-model="selectedCameraId" placeholder="选择摄像头" @change="handleCameraChange">
              <el-option
                  v-for="cam in cameraList"
                  :key="cam.id"
                  :label="cam.Name"
                  :value="cam.name"
              />
            </el-select>
            <AppButton type="success" @click="handleCompleteTask" :loading="isEndingTask">完成巡检</AppButton>
            <AppButton type="danger" require-confirm confirm-title="确定要终止巡检吗？" @click="handleAbortTask" :loading="isEndingTask">终止巡检</AppButton>
          </div>
        </el-card>

        <el-card shadow="never" class="info-card">
          <template #header>
            <div class="card-header">
              <span>车辆状态</span>
              <el-switch
                  v-model="isAgvRunning"
                  @change="toggleAgvStatus"
                  :loading="isTogglingAgv"
                  inline-prompt
                  :active-icon="CaretTop"
                  :inactive-icon="VideoPause"
              />
            </div>
          </template>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="车辆系统时间">{{ formatDateTime(agvStatus?.sysTime, 'hh:mm:ss') }}</el-descriptions-item>
            <el-descriptions-item label="已行驶距离">
              <span style="font-weight: bold; color: #409eff;">{{ agvStatus?.currentPosition?.toFixed(2) || '0.00' }}</span> 米
            </el-descriptions-item>
            <el-descriptions-item label="发现故障总数">
              <el-tag type="danger">{{ processedLiveFlaws?.length || 0 }}</el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card shadow="never" class="info-card">
          <template #header>
            <div class="card-header">实时故障列表</div>
          </template>
          <el-table :data="processedLiveFlaws" stripe style="width: 100%" height="250" empty-text="暂未发现故障">
            <el-table-column prop="flawName" label="故障名称" />
            <el-table-column prop="flawDistance" label="位置(m)" width="90" />
          </el-table>
        </el-card>
      </div>
    </div>

    <!-- 用户信息弹窗 -->
    <el-dialog
        v-model="userInfoDialogVisible"
        title="执行人变更通知"
        width="400px"
        :close-on-click-modal="false"
    >
      <div v-if="currentUserInfo" class="user-info-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="姓名">
            <el-tag type="primary">{{ currentUserInfo.name }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="性别">
            {{ currentUserInfo.gender }}
          </el-descriptions-item>
          <el-descriptions-item label="职业">
            {{ currentUserInfo.career }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="closeUserInfoDialog">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { useTasksStore } from '@/stores/tasks';
import { storeToRefs } from 'pinia';
import { usePolling } from '@/composables/usePolling';
import { ElPageHeader, ElCard, ElTable, ElTableColumn, ElDescriptions, ElDescriptionsItem, ElTag, ElIcon, ElSelect, ElOption, ElSwitch, ElTooltip, ElMessage, ElDialog, ElButton, vLoading } from 'element-plus';
import { VideoCamera, Van, Warning, CaretTop, VideoPause } from '@element-plus/icons-vue';
import { formatDateTime } from '@/utils';
import AppButton from '@/components/common/AppButton.vue';
import { getDeviceList, getHeartbeat, getLiveFlawInfo, agvForward, agvStop, getVideoStreamUrl } from '@/api/system';
import { endTask, getTask, getUserInfo } from '@/api/tasks';

const props = defineProps({
  id: { type: String, required: true },
});

const router = useRouter();
const tasksStore = useTasksStore();
const { currentTask, loading: taskLoading } = storeToRefs(tasksStore);

const videoPlayerContainer = ref(null);
const videoPlayerInstance = ref(null);
const cameraList = ref([]);
const selectedCameraId = ref(null);
const isAgvRunning = ref(false);
const isTogglingAgv = ref(false);
const isEndingTask = ref(false);

// 用户信息相关状态
const userInfoDialogVisible = ref(false);
const currentUserInfo = ref(null);
const currentExecutor = ref(null);

// --- Composables for Real-time Data ---
// 1. Polling for AGV status (heartbeat)
const { data: agvStatus, start: startHeartbeatPolling, stop: stopHeartbeatPolling } = usePolling(getHeartbeat, 1000);
// 2. Polling for live flaws
const { data: liveFlaws, error: flawError, start: startFlawPolling, stop: stopFlawPolling } = usePolling(() => getLiveFlawInfo(props.id), 3000);
// 3. Polling for task details to monitor executor changes
const { data: taskDetails, start: startTaskPolling, stop: stopTaskPolling } = usePolling(() => getTask(props.id), 2000);

// --- Computed Properties ---
const agvPositionPercentage = computed(() => {
  const totalDistance = currentTask.value?.taskTrip || 1;
  const currentPosition = agvStatus.value?.currentPosition || 0;
  const percentage = (currentPosition / totalDistance) * 100;
  return `${Math.max(0, Math.min(percentage, 100))}%`;
});

// 处理故障数据格式 - 确保返回数组
const processedLiveFlaws = computed(() => {
  if (!liveFlaws.value) {
    console.log('🔍 liveFlaws为空');
    return [];
  }

  return liveFlaws.value.data;
});

// --- Watch for executor changes ---
watch(taskDetails, async (newTaskDetails) => {
  if (newTaskDetails && newTaskDetails.data) {
    const newExecutor = newTaskDetails.data.executor;
    // 如果executor发生变化且不为空
    if (newExecutor && newExecutor !== currentExecutor.value && currentExecutor) {
      console.log('🔄 检测到executor变化:', currentExecutor.value, '->', newExecutor);
      currentExecutor.value = newExecutor;

      try {
        // 获取新executor的用户信息
        const userInfoRes = await getUserInfo(newExecutor);
        if (userInfoRes && userInfoRes.data) {
          currentUserInfo.value = userInfoRes.data.data;
          userInfoDialogVisible.value = true;
          ElMessage.success(`执行人已变更为: ${currentUserInfo.value.name}`);
        }
      } catch (error) {
        ElMessage.error('获取执行人信息失败！');
      }
    }
  }
}, { deep: true });

// --- Methods ---
const goBack = () => router.back();

const fetchCameraList = async () => {
  try {
    const res = await getDeviceList();
    cameraList.value = res.data.items || [];
    if (cameraList.value.length > 0) {
      selectedCameraId.value = cameraList.value[0].name;
    }
  } catch (error) {
    console.error("Failed to fetch camera list:", error);
    ElMessage.error("获取摄像头列表失败！");
  }
};


const initPlayer = (container, deviceId) => {
  if (!container || !deviceId) return;

  if (videoPlayerInstance.value) {
    videoPlayerInstance.value.destroy();
    videoPlayerInstance.value = null;
  }

  let streamUrl = getVideoStreamUrl(deviceId);
  console.log('视频流URL:', streamUrl);

  const easyplayer = new EasyPlayerPro(container, {
    libPath: "/js/",
    isLive: true,
    bufferTime: 0.2,
    stretch: false,
    MSE: false,
    WCS: false,
    hasAudio: true,
    watermark: {text: {content: 'easyplayer-pro'}, right: 10, top: 10},
  });

  videoPlayerInstance.value = easyplayer;

  setTimeout(() => {
    if (streamUrl && videoPlayerInstance.value) {
      videoPlayerInstance.value.play(streamUrl).then(() => {
        console.log('视频播放成功');
      }).catch((error) => {
        console.error('视频播放失败:', error);
        ElMessage.error('视频播放失败！');
      });
    }
  }, 100);
};

const getDeviceIdByName = (name) => {
  let deviceId = "";
  switch(name){
    case "摄像头1":
      deviceId = "P4DZ4oMHCT58m"
      break
    case "摄像头2":
      deviceId = "Px6xPlt2LQLVq"
      break
    case "摄像头3":
      deviceId = "PCJ08d8hzg970"
      break
    case "摄像头4":
      deviceId = "PbOUmNpZKCDFt"
      break
    default:
      deviceId = "" // Return empty for default
  }
  return deviceId;
}

watch(selectedCameraId, (newCameraName) => {
  if (newCameraName) {
    const deviceId = getDeviceIdByName(newCameraName);
    if (deviceId) {
      nextTick(() => {
        if (videoPlayerContainer.value) {
          initPlayer(videoPlayerContainer.value, deviceId);
        }
      });
    }
  }
}, { immediate: false }); // immediate: false, will be triggered by fetchCameraList setting the value

const handleCameraChange = (deviceName) => {
  // This function now just updates the reactive property,
  // the watcher will handle the player re-initialization.
  selectedCameraId.value = deviceName;
};

const toggleAgvStatus = async (isRunning) => {
  isTogglingAgv.value = true;
  try {
    if(isRunning) {
      // TODO: Implement the logic to start AGV
      await agvForward();
      ElMessage.success("AGV已启动前进");
    } else {
      await agvStop();
      ElMessage.info("AGV已停止");
    }
  } catch(error) {
    ElMessage.error("控制AGV失败！");
    isAgvRunning.value = !isRunning;
  } finally {
    isTogglingAgv.value = false;
  }
}

const handleCompleteTask = async () => {
  isEndingTask.value = true;
  try {
    await endTask({ id: props.id, isAbort: false }); //
    ElMessage.success("巡检任务已完成！");
    router.push(`/tasks/detail/${props.id}`);
  } catch (error) {
    ElMessage.error("完成任务失败！");
  } finally {
    isEndingTask.value = false;
  }
}

const handleAbortTask = async () => {
  isEndingTask.value = true;
  try {
    await endTask({ id: props.id, isAbort: true }); //
    ElMessage.warning("巡检任务已终止！");
    router.push(`/tasks`);
  } catch (error) {
    ElMessage.error("终止任务失败！");
  } finally {
    isEndingTask.value = false;
  }
}

// TODO: 没看懂
const calculateFlawPosition = (distance) => {
  const totalDistance = currentTask.value?.taskTrip || 1;
  const percentage = (distance / totalDistance) * 100;
  return `${Math.max(0, Math.min(percentage, 100))}%`;
};

// 关闭用户信息弹窗
const closeUserInfoDialog = () => {
  userInfoDialogVisible.value = false;
  currentUserInfo.value = null;
};

onMounted(async () => {
  await tasksStore.fetchTaskDetail(props.id);
  await fetchCameraList();
  let {data} = await getTask(props.id)
  currentExecutor.value = data.data.executor
  ElMessage.success(`当前任务执行人:${currentExecutor.value}`)
  startHeartbeatPolling();
  startFlawPolling();
  startTaskPolling();
});

onUnmounted(() => {
  // Clean up to prevent memory leaks
  stopHeartbeatPolling();
  stopFlawPolling();
  stopTaskPolling();
  if (videoPlayerInstance.value) {
    videoPlayerInstance.value.destroy();
    videoPlayerInstance.value = null;
  }
});
</script>

<style lang="scss" scoped>
@use '../assets/scss/variables' as *;

.task-execute-view {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: white;

  .el-page-header {
    padding: 16px 20px;
    border-bottom: 1px solid $border-color-light;
  }
}

.loading-state {
  flex: 1;
}

.main-container {
  flex: 1;
  display: flex;
  height: calc(100vh - 60px); // 减去头部高度
  overflow: hidden;
}

.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.video-area {
  flex: 1;
  background: #000;
  color: white;

  #player-box-dynamic {
    width: 100%;
    height: 100%;
  }

  .video-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 10px;
    color: $text-color-secondary;
    .el-icon { font-size: 48px; }
  }
}

.scale-bar-area { /* Styles from TaskDetailView */
  height: 120px;
  background: $fill-color-light;
  border-top: 1px solid $border-color-light;
  padding: 20px;
  display: flex;
  align-items: center;
}
.scale-bar-wrapper {
  position: relative;
  width: 100%;
}
.scale-bar {
  width: 100%;
  height: 8px;
  background: #e4e7ed;
  border-radius: $border-radius-base;
}
.scale-bar-progress {
  height: 100%;
  background: $primary-color;
  border-radius: $border-radius-base;
  transition: width 1s linear;
}
.scale-bar-text {
  position: absolute;
  font-size: $font-size-small;
  color: $text-color-regular;
  top: -10px;
  &.start { left: 0; }
  &.end { right: 0; }
}
.scale-bar-item {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 24px;
  height: 24px;
  border-radius: $border-radius-circle;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: white;
  cursor: pointer;
  border: 2px solid white;
  &.scale-bar-agv {
    background-color: $success-color;
    transform: translate(-50%, -50%);
    z-index: 10;
    animation: pulse 2s infinite;
  }
  &.scale-bar-flaw {
    background-color: $danger-color;
    transform: translate(-50%, -50%);
  }
}

.sidebar {
  width: $sidebar-width;
  border-left: 1px solid $border-color-light;
  display: flex;
  flex-direction: column;
  padding: 10px;
  gap: 10px;
  background: #fdfdfd;
  overflow-y: auto;
}

.info-card {
  border: none;
  background-color: white;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}
.control-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
  .el-select {
    flex: 1;
  }
}


@keyframes pulse {
  0% { box-shadow: 0 0 0 0 rgba($success-color, 0.7); }
  70% { box-shadow: 0 0 0 10px rgba($success-color, 0); }
  100% { box-shadow: 0 0 0 0 rgba($success-color, 0); }
}

// 用户信息弹窗样式
.user-info-content {
  .el-descriptions {
    margin-top: 10px;
  }

  .el-tag {
    font-weight: bold;
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
}
</style>